package com.gt.web.srv.web.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.gt.web.api.common.R;
import com.gt.web.srv.annotation.login.NoAuthorization;
import com.gt.web.srv.service.ISysConfigService;
import com.gt.web.srv.utils.GtConstants;
import com.gt.web.srv.utils.OptUtil;
import com.gt.web.srv.web.api.command.SchemaQrCodeCommand;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 公共接口
 *
 * @author Yu Chaohua
 * @date 2024/6/12 23:08
 */
@Slf4j
@RestController
@RequestMapping("/api/common/")
@Api(tags = "公共接口")
public class CommonController {

    @Resource
    private WxMaService wxMaService;



    @Resource
    private ISysConfigService sysConfigService;

    @NoAuthorization
    @PostMapping("/schemaQrCode")
    @ApiOperation(value = "生成小程序二维码", notes = "生成小程序二维码", position = 1)
    public R<byte[]> schemaQrCode(@Validated @RequestBody SchemaQrCodeCommand command) {
        byte[] qrCode = null;
        try {
            String envVersion = sysConfigService.selectConfigByKey(GtConstants.WX_MP_ENV_VERSION);
            if(!StrUtil.equalsIgnoreCase(envVersion, WxMaConstants.DEFAULT_ENV_VERSION) && StrUtil.isNotBlank(command.getEnvVersion())){
                envVersion = command.getEnvVersion();
            }
            qrCode = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(command.getScene(), command.getPagePath(), false,
                    StrUtil.blankToDefault(envVersion, WxMaConstants.DEFAULT_ENV_VERSION),
                    430, false, null, false);
        } catch (WxErrorException e) {
            log.error("获取小程序二维码失败:{}", e.getMessage());
            log.error("获取小程序二维码失败:", e);
            OptUtil.ifThrow(true, "获取二维码失败，" + e.getMessage());
        }
        return ObjectUtil.isNotNull(qrCode) ? OptUtil.successResponse(qrCode) : OptUtil.failResponse("获取小程序二维码失败");
    }

}
